<!-- 非法端口 -->
<template>
<div class="dashboard-editor-container">
  <el-row style="background: #fff; padding: 16px;">
    <div style="display:flex;justify-content:space-between;">
        <div >
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addClick()">添加规则</el-button>
        </div>
      </div>
    <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
      <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
      <el-table-column label="规则名称" prop="RuleName" align="left" show-overflow-tooltip width="160px"></el-table-column>
      <el-table-column label="应用对象" show-overflow-tooltip prop="DeviceObj" width="160px" align="left">
        <template slot-scope="{row}">
          <span v-if="row.DeviceObj ==''">全部</span>
          <span v-if="Array.isArray(row.DeviceObj)">{{ row.DeviceObj.join(',') }}</span>
          <span v-else>{{ row.DeviceObj }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="规则生效" show-overflow-tooltip prop="IsValid" align="left" width="160px">
        <template slot-scope="{row}">
          <!-- <span>{{ row.IsValid === 1 ? '生效' : '不生效' }}</span> -->
           <span style="color:#67C23A" v-if="row.IsValid === 1" type="success">生效</span>
           <span style="color:#F56C6C" v-else type="danger">停用</span>
        </template>
      </el-table-column>
      <el-table-column label="检测模式" show-overflow-tooltip prop="CheckType" align="left" width="160px">
        <template slot-scope="{row}">
          <!-- <span>{{ row.CheckType === 1 ? '白名单' : '黑名单' }}</span> -->
           <span style="color:#67C23A" v-if="row.CheckType === 1" type="success">白名单</span>
           <span style="color:#F56C6C" v-else type="danger">黑名单</span>
        </template>
      </el-table-column>
      <el-table-column label="检测间隔" show-overflow-tooltip prop="Interval" width="160px" align="left"></el-table-column>
      <el-table-column label="扫描端口" show-overflow-tooltip prop="Port"  align="left">
        <template slot-scope="scope">
            {{ formatPorts(scope.row.Port) }}
        </template>
      </el-table-column>
      <el-table-column label="备注信息" show-overflow-tooltip prop="Descp" align="left"></el-table-column>
      <el-table-column label="操作" align="left" width="150px">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="changeClick(scope.row, scope.$index)">修改</el-button>
          <el-button size="mini" type="danger" @click="deleteClick(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-row>
  <el-dialog
    top="5vh"
    :close-on-click-modal="false"
    :close-on-press-escape=false
    :title="Action === 1 ? '添加规则' : '修改规则' "
    :visible.sync="dialogVisible"
    v-el-drag-dialog
    width="600px">
      <el-form label-width="130px" :model="accountForm" :rules="rules" ref="accountForm">
        <el-row >
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='规则名称:' prop="RuleName">
              <el-input v-model.trim="accountForm.RuleName"  :disabled="Action !== 1" :maxlength="300"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='规则生效:' prop="IsValid">
              <el-switch v-model="accountForm.IsValid" :active-value="1" :inactive-value="0" active-color="#3a8adb" inactive-color="#ccc"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='应用对象:' prop="DeviceObjType">
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="1">全部</el-radio>
              <!-- <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="2">指定校区</el-radio> -->
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="8">指定角色</el-radio>
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="6">指定资产</el-radio>
              <el-select v-model="accountForm.DeviceObj" multiple style="width:100%" :placeholder="accountForm.DeviceObjType==1?'全部':'请选择'" :disabled="accountForm.DeviceObjType === 1">
                <el-option
                  v-for="(item,index) in accountForm.DeviceObjType ===6 ?assetList:DeviceObjList"
                  :key="index"
                  :label="item.DeviceName"
                  :value="item.DeviceName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label="备注信息" prop="Descp">
              <el-input placeholder="请输入备注" type="textarea" :rows="3"  v-model="accountForm.Descp"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="19" :sm="19" :lg="19">
            <el-form-item label='检测间隔:' prop="Interval">
              <el-input v-model="accountForm.Interval"  oninput="value=value.replace(/[^0-9]/g,'')"  maxlength="9"><span slot="append">秒钟</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='检测模式:' prop="CheckType">
              <el-radio v-model="accountForm.CheckType"   :label="1">白名单</el-radio>
              <el-radio v-model="accountForm.CheckType"   :label="0">黑名单</el-radio>
              
              
            </el-form-item> 
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item  prop="Port">
              <el-input placeholder="请输入扫描的端口/终端" value="12" type="textarea" :rows="3"  v-model="accountForm.Port" @input="validateInput"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form> 
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
</div>
</template>

<script>
import { connrequest } from '@/api/firstPage'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
directives: { elDragDialog },
data() {
return {
  pageNum: 1,
  pageSize: 10,
  tableData: [],
  Action: 1,
  dialogVisible: false,
  accountForm: {
  },
  DeviceObjList: [],
  assetList:[],
  rules: {
    RuleName: [
      { required: true, message: "请输入规则名称"}
    ],
    Port: [
      { 
        validator: (rule, value, callback) => {
          // 将输入按换行符拆分成数组
          if (value === undefined) {
            // 输入值为 undefined，直接返回成功
            callback();
            return;
          }
          const ports = value.split(/\n/);
          let valid = true;
          // 遍历每个端口号
          ports.forEach(port => {
            // 移除空白字符
            port = port.trim();
            // 检查是否是介于 1 到 65535 之间的整数
            const intValue = parseInt(port);
            if (isNaN(intValue) || intValue < 1 || intValue > 65535) {
              valid = false;
            }
          });
          // 根据验证结果调用 callback
          if (valid) {
            callback();
          } else {
            callback(new Error("端口输入介于 1 到 65535 之间的整数"));
          }
        },
        trigger: 'blur', // 触发时机，可以根据需要调整
        message: "端口输入介于1 到 65535 之间的整数"
      }
    ]
  }
}
},
//生命周期 - 创建完成（访问当前this实例）
created() {
  this.getData()
  this.CenterGetDevice()
},
//生命周期 - 挂载完成（访问DOM元素）
mounted() {

},
methods: {
  async getData(){
    // GetListenPortRule
    const res = await connrequest('GetListenPortRule')
    // console.log(this.tableData);
    this.tableData = res.Data
    
  },
  async CenterGetDevice(){
    const data = {
      Paging:{
        QueryPageNo: 1,
        QueryPageLength: 100000000
      },
      Filter:{
        Status: 0,
      }
    }
    const res = await connrequest('CenterGetDevice', data)
    this.assetList = res.Data
  },
   formatPorts(ports) {
    if (Array.isArray(ports)) {
      return ports.join(', ');  // 如果要在端口号之间添加空格，可以使用 "ports.join(' ')"
    } else if (typeof ports === 'string') {
      // 如果端口作为字符串存储，可以根据具体的分隔符进行拆分
      return ports.split('\n').join(', ');  // 例如，如果是用逗号分隔的字符串，则可以使用.split(',')来拆分
    } else {
      return ports; // 其他情况下，原样返回
    }
  },
  async DeviceObjTypeChange(value){
    this.$set(this.accountForm, 'DeviceObj', '')
    if(value === 1){
      this.DeviceObjList = []
    }else if(value === 2){
      const res = await this.GetSchoolStatusSumTree()
      this.DeviceObjList = [res]
    }else if(value === 8){
      const res = await this.GetRolestatus()
      var arr = []
      res.map(item => {
        var val ={'DeviceName': item.Role}
        arr.push(val)
      })
      this.DeviceObjList = arr
    }else{
      const res = await this.GetDeviceStatusSumTree()
      this.DeviceObjList = [res]
    }
  },
  // 获取校区树
  async GetSchoolStatusSumTree() {
    const res = await connrequest('GetSchoolStatusSumTree')
    return this.transformData(res.Data)
  },
  // 获取角色
  async GetRolestatus() {
    const res = await connrequest('GetParamDictRole')
    return res.Data
  },
  // 获取资产树
  async GetDeviceStatusSumTree() {
    const res = await connrequest('GetDeviceStatusSumTree')
    return this.transformData(res.Data)
  },
  transformData(inputData) {
    const { RootName, PrimArea} = inputData;
      return {
        SubClass: RootName,
        value: RootName,
        level: 1,
        children: PrimArea.map(area => ({
          SubClass: area.PrimAreaName,
          value: area.PrimAreaName,
          level: 2,
          children: area.SecondArea.map(secondArea => ({
            SubClass: secondArea.SecondAreaName,
            value: secondArea.SecondAreaName,
            level: 3,
        }))
      }))
    }
  },
  handleChange(row){
    // console.log(row);
  },
  // 获取子节点的校区
  async lazyLoad(node, resolve){
    if(node.level < 3){
      resolve(node.data) 
    }else{
      const data = {
        Paging:{
          QueryPageNo: 1,
          QueryPageLength: 100000
        },
        Filter:{
          SecondArea: node.label,
        }
      }
      const res = await connrequest('GetSchool', data)
      let arr = []
      res.Data.map(item => {
        arr.push( {SubClass: item.SchoolName, value: item.SchoolName, level: 4, children: undefined} )
      })
      resolve(arr) 
    }
  },
  // 获取子节点的资产
  async lazyLoad2(node, resolve){
    if(node.level < 3){
      resolve(node.data) 
    }else{
      const data = {
        Paging:{
          QueryPageNo: 1,
          QueryPageLength: 100000
        },
        Filter:{
          SecondArea: node.label,
        }
      }
      const res = await connrequest('CenterGetDevice', data)
      let arr = []
      res.Data.map(item => {
        arr.push( {SubClass: item.DeviceName, value: item.DeviceName, level: 4, children: undefined} )
      })
      resolve(arr) 
    }
  },
 addClick() {
    this.Action = 1;

    this.$nextTick(() => {
      // 等待组件挂载
      if (this.$refs['accountForm']) {
        this.accountForm = {
          IsValid: 1,
          DeviceObjType: 1,
          CheckType:1,
          Interval: 60,
          DeviceObj: [],
        };
        this.$refs['accountForm'].resetFields();
        
      } else {
        // console.error('Error: $refs["accountForm"] is still undefined.');
        this.accountForm = {
        IsValid: 1, 
        DeviceObjType: 1,
        CheckType:1,
        Interval: 60,
        DeviceObj: []
      };
      }
      this.dialogVisible = true;
    });
  },
  validateInput() {
    // 使用正则表达式验证输入，允许整数和换行
    this.accountForm.Port = this.accountForm.Port.replace(/[^\d\n]/g, "");
  },
  changeClick(row, index){
    // console.log(row.Port);
    if (Array.isArray(row.Port)) 
      row.Port = row.Port.join('\n')
    this.Action = 2
    this.$nextTick(()=>{
      this.accountForm = {...row}
      this.$refs['accountForm'].resetFields();
    })
    this.dialogVisible = true
  },
  deleteClick(row){
    this.$confirm('此操作将永久删除该规则, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      let data = {
        Data: {
          Action: 3,
          Detail: {...row}
        }
      }
      const res = await connrequest('EditListenPortRule', data)
      if(res.Status.StatusCode === 0){
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.getData()
        this.dialogVisible = false
      }
    }).catch(() => {
      this.$message({
        type: 'info',
        message: '已取消删除'
      });          
    });
  },
  submit(){
    this.$refs['accountForm'].validate( async(valid) => {
      if(valid){
        if(this.accountForm.DeviceObjType === 2){
          if(!this.accountForm.DeviceObj) {
            this.$message.error('请选择校区')
            return false
          }
        }
        if(this.accountForm.DeviceObjType === 8){
          if(!this.accountForm.DeviceObj) {
            this.$message.error('请选择角色')
            return false
          }
        }
        if(this.accountForm.DeviceObjType === 6){
          if(!this.accountForm.DeviceObj) {
            this.$message.error('请选择资产')
            return false
          }
        }
        let data = {
        Data: {
        Action: this.Action,
        Detail:{...this.accountForm,Port:this.accountForm.Port != undefined?this.accountForm.Port.split('\n').map(item => parseInt(item, 10)).filter(value => !isNaN(value)):[]}
        }
    }
    
    // console.log("确定",data);
    const res = await connrequest('EditListenPortRule', data)
    if(res.Status.StatusCode === 0){
      this.$message.success(this.Action==1?'添加成功':'修改成功')
      this.getData()
      this.dialogVisible = false
    }
     }
  })
  },
}
}
</script>
<style scoped>
/* @import url(); 引入css类 */
.el-dialog__title::before {
  padding-left: 30px; /* 调整标题和图标的距离 */
  background-image: url('../../assets/logo.png'); /* 指定图标路径 */
  background-repeat: no-repeat; /* 防止背景图片重复 */
  background-position: left center; /* 将图标放在标题左侧中间 */
}

</style>